﻿using System.Collections.Generic;
using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class EditPluginTemplateLiteralsPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IEditPluginTemplateLiteralsView _view;

        public EditPluginTemplateLiteralsPresenter(IEditPluginTemplateLiteralsView view)
            : this(view, new RepositoryFactory())
        {
        }

        public EditPluginTemplateLiteralsPresenter(IEditPluginTemplateLiteralsView view,
                                                    IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.EditPluginTemplateLiterals)
                _view.RedirectToPermissionDeniedPage();
        }
        
        public void Initialize()
        {
            PluginTemplate template = SystemRepository.GetPluginTemplate(_view.TemplateID);
            _view.PluginID = template.Plugin.ID;
            _view.SetLiterals(template.Literals);
        }

        public IList<Locale> GetLocales()
        {
            return _administrator.CurrentSite.Locales;
        }

        public void Save()
        {
            //...
            if (!IsValid)
                return;
            PluginTemplate template = SystemRepository.GetPluginTemplate(_view.TemplateID);
            foreach (PluginTemplateLiteral l in _view.GetTranslations())
            {
                foreach (var kvp in l.Translations)
                {
                    PluginTemplateLiteral literal = template.GetLiteral(l.ID);
                    literal.SetHtml(kvp.Key, kvp.Value.Html);
                }
            }
            SystemRepository.SavePlugin(template.Plugin);
        }
    }
}